import { userLogin } from '@/apis/user'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import $router from "@/router"
import { cartMergeCart } from '@/apis/cart'
import { useCartStore } from './cart'
export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const getUserInfo = async ({ account, password }) => {
    const res = await userLogin({ account, password })

    userInfo.value = res.data.result
    if (userInfo.value.token) {
      ElMessage.success('登录成功')
      //TODO: 跳转到首页
      $router.replace('/')
    }
    // 合并购物车操作
    const cartStore = useCartStore()
    const arr = cartStore.cartList.map(({ skuId, selected, count }) => { skuId, selected, count })
    await cartMergeCart(arr)
    // 重新获取购物车列表数据
    cartStore.getCartList()
  }
  const setUserInfo = (obj) => userInfo.value = obj
  return {
    userInfo, getUserInfo, setUserInfo
  }


},
  {
    persist: true,
  })
